import * as React from 'react'
import { Provider } from 'react-redux'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import { IRoutes, loadable, routes } from 'routes'
import { PersistGate } from 'redux-persist/integration/react'
import { store, persistor } from 'store'
import { ScrollContext } from 'react-router-scroll-4'
import Home from './store/action/Home'
import Search from './views/Search'

// 登录验证
function requireAuth(Layout: any, props: any, login: boolean) {
    if (login) { // 需要验证登录
        const data: any = store.getState()
        const { history } = props
        if (!data.user.userInfo.id) {
            history.push('/loginMode')
            return <Layout {...props} />
        }
    }
    return <Layout {...props} />
}
class App extends React.Component {
    public render() {
        return (
            <Provider store={store}>
                <PersistGate loading={null} persistor={persistor}>
                    <BrowserRouter>
                        <ScrollContext>
                            <Switch>
                                <Route path="/" exact={true} component={Home} />
                                <Route path="/search" component={Search} />
                                {
                                    routes.map((item: IRoutes, index: number) => {
                                        const val = item.login === undefined ? true : item.login
                                        return (
                                            <Route
                                                path={item.path}
                                                key={index}
                                                component={(props: any) => requireAuth(loadable(item.component), props, val)}
                                            />
                                        )
                                    })
                                }
                            </Switch>
                        </ScrollContext>
                    </BrowserRouter>
                </PersistGate>
            </Provider>
        )
    }
}

export default App